<?php

namespace api\modules\app\services;

use api\components\Common;
use api\modules\app\models\DeployDetail;
use api\modules\app\models\Qrcode;
use api\modules\app\models\QrcodeBind;
use api\modules\app\models\QrcodeDeploy;
use api\modules\app\models\QrcodeRecord;
use api\modules\app\models\QrcodeTag;
use api\modules\app\models\Unit;
use api\utils\ExportUtil;
use api\utils\FileUtil;
use api\utils\LogUtil;
use api\utils\StringUtil;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;
use Exception;
use InvalidArgumentException;
use Yii;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;
use yii\helpers\FileHelper;
use ZipArchive;

class QrcodeService
{
    public static function unBind($unitCode)
    {
        $trans = Yii::$app->test_3->beginTransaction();
        try {
            $qrcode = Qrcode::findOne(['bind_code' => $unitCode]);
            if (empty($qrcode)) {
                $trans->commit();
                return;
            }
            $qrcode->setAttributes([
                'has_bind' => 0,
                'bind_code' => null,
                'bind_at' => null,
                'bind_user' => null,
                'bind_username' => null,
                'bind_lng' => null,
                'bind_address' => null,
                'bind_lat' => null,
                'event_type1' => null,
                'event_type1_code' => null,
                'event_type2' => null,
                'event_type2_code' => null,
                'event_type3' => null,
                'event_type3_code' => null,
                'unit_name' => null,
                'unit_name_code' => null,
                'images' => null,
            ]);
            $qrcode->save();
            Unit::updateAll(['has_bind' => 0, 'qrcode' => null], ['unit_code' => $unitCode]);
            $batchQrcode = QrcodeRecord::findOne(['id' => $qrcode->batch_code]);
            $batchQrcode->bind_count = ($batchQrcode->bind_count - 1) > 0 ? $batchQrcode->bind_count : 0;
            $batchQrcode->save();
            $trans->commit();
            return true;
        }catch (\Exception $e){
            $trans->rollBack();
            throw new \Exception($e->getMessage());
        }
    }

    public static function batchCreate(QrcodeRecord $batch, $params) {
        set_time_limit(60);
        $currentTime = time();
        $needImage = $params['needImage'] ?? true;

        $snowflake = Yii::$app->snowflake;
        $codes = [];
        for ($i=0; $i < $batch->count; $i++) {
            $id = $snowflake->id();
            if ($needImage) {
                list($files[$id], $path, $localPath) = self::createFile($id);
            }
            $codes[] = [
                'batch_code' => $batch->id,
//                'tag_code' => $batch->tag_code,
//                'tag_name' => $batch->tag_name,
                'code' => $id,
                'state' => 1,
//                'path' => $path ?? '',
                'path' => $localPath ?? '',
            ];
        }
        Yii::$app->test_3->createCommand()
            ->batchInsert(Qrcode::tableName(), array_keys($codes[0]), $codes)
            ->execute();

        if (!empty($params['tag_codes'])) {
            $tagCodes = $params['tag_codes'];
            if (!is_array($tagCodes)) {
                $tagCodes = explode(',', $tagCodes);
            }

            $data = [];
            $qrcodes = Qrcode::find()->select(['code'])->where(['batch_code'=>$batch->id])->column();
            foreach ($qrcodes as $qrcode) {
                foreach ($tagCodes as $tagCode) {
                $tagName = QrcodeTag::getTagCodeByKey($tagCode);
                    $data[] = [
                        'qrcode' => $qrcode,
                        'tag_code' => $tagCode,
                        'tag_name' => $tagName,
                        'is_delete' => 0,
                        'create_time' => $currentTime,
                        'update_time' => $currentTime,
                    ];
                }
            }

            Yii::$app->test_3->createCommand()
                ->batchInsert(QrcodeTag::tableName(), array_keys($data[0]), $data)
                ->execute();
        }

        if (!$needImage) {
            return '';
        }

        $zip = new ZipArchive();
        $filePath = Yii::$app->getRuntimePath() . DIRECTORY_SEPARATOR . 'qrcode_batch' . DIRECTORY_SEPARATOR;
        $zipFile = $batch->id . '.zip';
        $zipFilename = FileUtil::createFile('qrcode_batch' . DIRECTORY_SEPARATOR, $zipFile);
        if (($code = $zip->open($filePath . $zipFile, ZIPARCHIVE::CREATE)) !== TRUE) {
            throw new Exception('添加二维码压缩文件失败' . $code);
        }
        foreach ($files as $name => $file) {
            $zip->addFile($file, "$name.png");
        }
        $zip->close();
        return $localPath;
    }

    public static function batchCreate2($count, $batchCode, $needImage = false)
    {
        $snowflake = Yii::$app->snowflake;
        $codes = [];
        for ($i=0; $i < $count; $i++) {
            $id = $snowflake->id();
            if ($needImage) {
                list($files[$id], $path, $localPath) = self::createFile($id);
            }
            $codes[] = [
                'batch_code' => $batchCode,

                'code' => $id,
                'state' => 1,
//                'path' => $path ?? '',
                'path' => $localPath ?? '',
            ];
        }
        Yii::$app->test_3->createCommand()
                        ->batchInsert(Qrcode::tableName(), array_keys($codes[0]), $codes)
                        ->execute();

        if (!$needImage) {
            return '';
        }

        $zip = new ZipArchive();
        $filePath = Yii::$app->getRuntimePath() . DIRECTORY_SEPARATOR . 'qrcode_batch' . DIRECTORY_SEPARATOR;
        $zipFile = $batchCode . '.zip';
        $zipFilename = FileUtil::createFile('qrcode_batch' . DIRECTORY_SEPARATOR, $zipFile);
        // if (file_exists($filePath . $zipFile)) {
        //     return 'qrcode_batch' . DIRECTORY_SEPARATOR . $zipFile;
        // }
        if (($code = $zip->open($filePath . $zipFile, ZIPARCHIVE::CREATE)) !== TRUE) {
            throw new Exception('添加二维码压缩文件失败' . $code);
        }
        foreach ($files as $name => $file) {
            $zip->addFile($file, "$name.png");
        }
        $zip->close();
//        $file = new \SplFileObject($zipFilename);
//        $response = Yii::$app->fileServer->uploadFile($file);
        return $localPath;

//        return $response['path'];
        // return 'qrcode_batch' . DIRECTORY_SEPARATOR . $zipFile;
    }

    private static function createFile($id)
    {

        $url = 'https://jacode.iotsh.com.cn:18081/ja/code/index.html?code='.$id;

        $result = Builder::create()
                        ->writer(new PngWriter())
                        ->writerOptions([])
                        ->data($url)
                        ->encoding(new Encoding('UTF-8'))
                        ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
                        ->size(300)
                        ->margin(10)
                        ->roundBlockSizeMode(new RoundBlockSizeModeMargin())
                        // ->logoPath(__DIR__.'/assets/symfony.png')
                        // ->labelText('编号：' . $item['code'])
                        // ->labelFont(new NotoSans(20))
                        // ->labelAlignment(new LabelAlignmentCenter())
                        ->build();

        // Save it to a file
        $path = 'qrcode' . DIRECTORY_SEPARATOR;
        $filename = $id . '.png';
        $fullName = FileUtil::createFile($path, $filename);
        $localPath = $path . $filename;
        $result->saveToFile($fullName);

        return [$fullName, '', $localPath];

//        $file = new \SplFileObject($fullName);
//        $response = Yii::$app->fileServer->uploadFile($file);
//
//        return [$fullName, $response['path'], $localPath];
    }

    public function searchBatch($params)
    {
        $query = QrcodeRecord::find()->orderBy(['id' => SORT_DESC]);
        $condition = [];
        if (!StringUtil::isEmpty($params['id'])) {
            $condition[] = ['id' => $params['id']];
        }
        if (!StringUtil::isEmpty($params['start'])) {
            $condition[] = ['between', 'created_at', date('Y-m-d H:i:s', $params['start']), date('Y-m-d H:i:s', $params['end'])];
        }
        foreach ($condition as $cond) {
            $query->andFilterWhere($cond);
        }
        $query->select(['*'])->asArray();
        return new ActiveDataProvider([
            'query' => $query,
            'pagination' => new Pagination([
                'pageSize' => $params['per-page'],
                'page' => $params['page'] - 1,
            ]),
            'sort' => false
        ]);
    }

    public function list($params) {
        $count = $this->search($params, true);
        $data = $this->search($params);

        $qrcodes = array_column($data,'code');
        $res1 = QrcodeTag::find()->where(['is_delete'=>0,'qrcode'=>$qrcodes])->asArray()->all();
        $res2 = QrcodeBind::find()->where(['is_delete'=>0,'qrcode'=>$qrcodes])->asArray()->all();
        $unitCodes = array_column($res2, 'unit_code');
        $res3 = Unit::find()->where(['status'=>1,'unit_code'=>$unitCodes])->asArray()->all();
        $tags = [];
        $binds = [];
        $units = [];
        if (!empty($res1)) {
            foreach ($res1 as $v) {
                $tags[$v['qrcode']][] = $v;
            }
        }
        if (!empty($res2)) {
            foreach ($res2 as $v) {
                $binds[$v['qrcode']][] = $v;
            }
        }
        if (!empty($res3)) {
            foreach ($res3 as $v) {
                $units[$v['unit_code']] = $v;
            }
        }


        $unitFields = ['name', 'name_code', 'loc_type_code', 'loc_type_name', 'loc_name', 'event_type1', 'event_type1', 'event_type1_code', 'event_type2', 'event_type2_code', 'event_type3', 'event_type3_code',];
        foreach ($data as &$v) {
            $v['tag_text'] = array_key_exists($v['code'], $tags) ? implode(',',array_column($tags[$v['code']],'tag_name')) : '';
            $v['binds'] = array_key_exists($v['code'], $binds) ? $binds[$v['code']] : [];

            if (!empty($v['binds'])) {
                foreach ($v['binds'] as $k1 => $v1) {
                    if (array_key_exists($v1['unit_code'], $units)) {
                        $unit = $units[$v1['unit_code']];
                        foreach ($unitFields as $f) {
                            $v['binds'][$k1][$f] = $unit[$f];
                        }
                    }
                }
            }

            $v['has_bind'] = self::hasQrcodeBind($v['code']);
        }

         $result['_meta']['totalCount'] = $count;
         $result['data'] = $data;

        return $result;
    }

    public function search($params, $count = false) {
        $params['state'] = 1;
        $query = $this->genQuery($params);
        $query->orderBy(['id' => SORT_DESC]);
        if ($count) {
            return $query->count();
        }

        Common::constructPage($query, $params);
        return $query->asArray()->all();
    }

    private function genQuery($params)
    {
        $query = Qrcode::find();
        $condition = [];
        if (!empty($params['ids'])) {
            $condition[] = ['id' => $params['ids']];
        }
        if (!StringUtil::isEmpty($params['state'])) {
            $condition[] = ['state' => $params['state']];
        }
        if (!StringUtil::isEmpty($params['code'])) {
            $condition[] = ['code' => $params['code']];
        }
        if (!StringUtil::isEmpty($params['batchCode'])) {
            $condition[] = ['batch_code' => $params['batchCode']];
        }
        if (!StringUtil::isEmpty($params['bindStart'])) {
            $condition[] = ['between', 'bind_at', date('Y-m-d H:i:s', $params['bindStart']), date('Y-m-d H:i:s', $params['bindEnd'])];
        }
        if (!StringUtil::isEmpty($params['hasBind'])) {
            $condition[] = ['qrcode.has_bind' => $params['hasBind']];
        }
        if (!StringUtil::isEmpty($params['start'])) {
            $condition[] = ['between', 'created_at', date('Y-m-d H:i:s', $params['start']), date('Y-m-d H:i:s', $params['end'])];
        }
        if (!StringUtil::isEmpty($params['eventType'])) {
            $condition[] = ['qrcode.has_bind' => 1];
            $condition[] = ['qrcode.event_type3_code' => $params['eventType']];
        }

        foreach ($condition as $cond) {
            $query->andFilterWhere($cond);
        }
        return $query;
    }

    public function exportCode($params)
    {
        $params['state'] = 1;
        $query = $this->genQuery($params);
        $query->orderBy(['id' => SORT_DESC]);
        $rows = [];
        $header = '二维码编码,二维码批次码,二维码文件,是否绑定部件,绑定部件编码,二维码创建时间';
        foreach ($query->each() as $item) {
            $rows[] = [
                'code' => $item['code'],
                'batch_code' => $item['batch_code'],
                'path' => $item['path'],
                'has_bind' => empty($item['has_bind']) ? '否' : '是',
                'bind_code' => $item['bind_code'],
                'createdAt' => $item['created_at'],
            ];
        }

        $filename = 'export_' . date('Y-m-d') . '_' . uniqid() . '.csv';
        $file = ExportUtil::exportCsv($filename, explode(',', $header), $rows);
        $localPath = '/exportfile/'.date('Y-m-d').'/'.$filename;
        return ['url' => $localPath];


//        if (YII_ENV == 'prod' || YII_ENV == 'uat') {
//            $response = Yii::$app->fileServer->uploadFile($file);
//            @unlink($file->getRealPath());
//        }
//
//        return [
//            'url' => $response['path'] ?? "exportfile/${filename}",
//        ];
    }

    public function export($params)
    {
        $params['state'] = 1;
        $query = $this->genQuery($params);
        $count = $query->count();
        if ($count>100) {
            throw new InvalidArgumentException('最多导出100张');
        }

        $data = $query->orderBy(['id' => SORT_DESC])->all();
        if (empty($data)) {
            throw new InvalidArgumentException('没有选中的数据需要导出');
        }
        $basePath = Yii::$app->getRuntimePath() . DIRECTORY_SEPARATOR . 'qrcode' . DIRECTORY_SEPARATOR;
        FileHelper::createDirectory($basePath);
        $failed = [];
        foreach ($data as $qrcode) {
            $filename = $basePath . $qrcode['code'] . '.png';
            $files[$qrcode['code']] = $filename;
        }
        $zipBasePath = Yii::$app->getRuntimePath() . DIRECTORY_SEPARATOR . 'qrcode_zip';

        $zip = new ZipArchive();
        $zipName = '/export_qrcode_' . time() . '.zip';
        $exportFile = $zipBasePath . $zipName;
        if (($code = $zip->open($exportFile, ZIPARCHIVE::CREATE)) !== TRUE) {
            throw new Exception('添加二维码压缩文件失败' . $code);
        }

        if (isset($params['exportTypeTl']) && $params['exportTypeTl'] == 2) {
            $mergePath =  Yii::$app->getRuntimePath().'/qrcode_merge';
            foreach ($files as $name => $file) {
                list($file,$localName) = $this->createMergeImage($file,$name,$mergePath);
                $zip->addFile($file, $localName);
            }

//            $zipBasePath = Yii::$app->getRuntimePath() . DIRECTORY_SEPARATOR . 'qrcode_zip';
        } else {
            foreach ($files as $name => $file) {
                $zip->addFile($file, "$name.png");
            }
        }

        $zip->close();
        $zipFile = new \SplFileObject($exportFile);

        return [
            'url' => '/qrcode_zip'.$zipName,
            'name' => $zipName,
            'total' => count($data),
            'success' => count($data) - count($failed),
            'fails' => $failed ?? [],
        ];
    }

    public function createMergeImage($avatarUrl,$name,$mergePath) {
        $thumb = imagecreatetruecolor(600,600);
        $img_content = imagecreatefrompng($avatarUrl);//获取图片资源
        imagecopyresampled($thumb, $img_content, 0, 0, 0, 0, 600, 600, 320, 320);//核心函数，改变图片大小
        $file_name = "{$mergePath}/{$name}_qrcode.png";
        imagepng($thumb,$file_name);//将图片资源保存到qrcode.png中
        $img = '/jam.jpg';
        $imgs = imagecreatefromjpeg(getcwd().$img);
        imagecopy($imgs, $thumb, 930, 2210, 0, 0, 600, 600);//核心函数：复制图片资源到另一图片资源中
        $localName = "{$name}_last.jpg";
        $f_file_name = "{$mergePath}/{$localName}";
        imagejpeg($imgs,$f_file_name); //保存
        imagedestroy($imgs);
        imagedestroy($thumb);//销毁图片资源
        return [$f_file_name,$localName];
    }

    public function export22222($params)
    {
        $params['state'] = 1;
        $query = $this->genQuery($params);
        $data = $query->orderBy(['id' => SORT_DESC])->all();
        if (empty($data)) {
            throw new InvalidArgumentException('没有选中的数据需要导出');
        }
        $basePath = Yii::$app->getRuntimePath() . DIRECTORY_SEPARATOR . 'qrcode' . DIRECTORY_SEPARATOR;
        FileHelper::createDirectory($basePath);
        $fileServe = Yii::$app->fileServer;
        $failed = [];
        foreach ($data as $qrcode) {
            $filename = $basePath . $qrcode['code'] . '.png';
            try {
                $fullName = $fileServe->getFileByShort($qrcode['path'], $filename);
            } catch (\Throwable $th) {
                LogUtil::warn(['qrcode export get file error']);
                $fullName = null;
            }
            if ($fullName) {
                $files[$qrcode['code']] = $filename;
            } else {
                $failed[] = $qrcode['code'];
            }
        }
        $zip = new ZipArchive();
        $exportFile = 'export_qrcode_' . time() . '.zip';
        if (($code = $zip->open($exportFile, ZIPARCHIVE::CREATE)) !== TRUE) {
            throw new Exception('添加二维码压缩文件失败' . $code);
        }
        foreach ($files as $name => $file) {
            $zip->addFile($file, "$name.png");
        }
        $zip->close();
        $zipFile = new \SplFileObject($exportFile);
        $response = $fileServe->uploadFile($zipFile);
        @unlink($exportFile);

        return [
            'url' => $response['path'],
            'total' => count($data),
            'success' => count($data) - count($failed),
            'fails' => $failed ?? [],
        ];
    }

    public function bind($code, $params, $user) {
        \Yii::error('qrcode_bind_start======'.json_encode([$code, $params, $user]));
        $dateTime = date('Y-m-d H:i:s', time());
        $transaction = Yii::$app->test_3->beginTransaction();
        try {
            $qrcode = Qrcode::findOne(['code' => $code]);
            if (empty($qrcode)) {
                throw new InvalidArgumentException('二维码不存在');
            }

            //驼峰改下划线 unit_code
            if (isset($params['unit_code']) && !empty($params['unit_code'])) {
                $unit = Unit::findOne(['unit_code' => $params['unit_code']]);
            } elseif (isset($params['outer_code']) && !empty($params['outer_code'])) {
                $unit = Unit::findOne(['outer_code' => $params['outer_code']]);
            }
            if (empty($unit)) {
                throw new InvalidArgumentException('部件未找到');
            }

            $qrcodeBind = QrcodeBind::find()->where(['qrcode'=>$code,'type'=>$unit->type,'is_delete'=>0])->one();
            if (!empty($qrcodeBind)) {
                return [
                    'status' => $qrcodeBind->unit_code == $params['unit_code'] ? 1 : 0,
                    'qrcode' => $qrcode,
                ];
            }

            //部件绑定过了
            $qrcodeBind = QrcodeBind::find()->where(['unit_code'=>$params['unit_code'],'is_delete'=>0])->one();

            if (!empty($qrcodeBind)) {
                return [
                    'status' => 2,
                    'qrcode' => $qrcode,
                    'unit' => $unit,
                ];
            }

            $qrcodeBind = new QrcodeBind();

            $bindImgs = empty($params['images']) ? [] : implode(',', $params['images']);
//print_r($bindImgs);exit;
            $qrcodeBind->setAttributes([
                'qrcode' => $code,
                'unit_code' => $unit->unit_code,
                'bind_user' => $user['id'] ?? 0,
                'bind_username' => $user['username'] ?? '',
                'bind_code' => $unit->unit_code,
                'bind_address' => $params['address']??'',
                'bind_at' => $dateTime,
                'created_at' => $dateTime,
                'event_type1' => $unit->event_type1,
                'event_type1_code' => $unit->event_type1_code,
                'event_type2' => $unit->event_type2,
                'event_type2_code' => $unit->event_type2_code,
                'event_type3' => $unit->event_type3,
                'event_type3_code' => $unit->event_type3_code,
                'unit_name' => $unit->name,
                'unit_name_code' => $unit->name_code,
                'images' => $bindImgs,
                'type' => $unit->type,
            ]);
            if (!StringUtil::isEmpty($params['lat'])) {
                $qrcodeBind->bind_lat = $params['lat'];
            }
            if (!StringUtil::isEmpty($params['lng'])) {
                $qrcodeBind->bind_lng = $params['lng'];
            }

            $qrcodeBind->save();

            $qrcode->has_bind = 1;
            $qrcode->save();

            $unit->has_bind = 1;
            $unit->images = $bindImgs;
            $unit->qrcode = $qrcode->code;
            $unit->bind_at = $dateTime;
            $unit->save(true);

            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            \Yii::error('qrcode_bind======'.json_encode([$code, $params, $user]).$e->getMessage());
            throw new \Exception($e->getMessage());
        }

        //@todo srq
        $this->updateDeploy($unit);
        $this->updateRecord($qrcode->batch_code);

        return [
            'status' => 1,
            'qrcode' => $qrcode,
            'unit' => $unit,
        ];
    }

    /**
     * @return [
     *      'status' => 0, // 0 绑定失败，1，绑定成功，
     *      'qrcode' => Qrcode
     * ]
     */
    public function bind22222($code, $params, $user)
    {
        $transaction = Yii::$app->test_3->beginTransaction();
        try {
            $qrcode = Qrcode::findOne(['code' => $code]);
            if (empty($qrcode)) {
                throw new InvalidArgumentException('二维码不存在');
            }
            $unit = Unit::findOne(['unit_code' => $params['unitCode']]);
            if (empty($unit)) {
                throw new InvalidArgumentException('部件未找到');
            }
            if ($qrcode->has_bind) {
                return [
                    'status' => $qrcode->bind_code == $params['unitCode'] ? 1 : 0,
                    'qrcode' => $qrcode,
                ];
            }
            if ($unit->has_bind) {
                return [
                    'status' => 2,
                    'qrcode' => $qrcode,
                    'unit' => $unit,
                ];
            }
            $bindImgs = empty($params['images']) ? [] : implode(',', $params['images']);
            $qrcode->setAttributes([
                'has_bind' => 1,
                'bind_user' => $user['id'],
                'bind_username' => $user['username'],
                'bind_code' => $unit->unit_code,
                'bind_address' => $params['address'],
                'bind_at' => date('Y-m-d H:i:s', time()),
                'event_type1' => $unit->event_type1,
                'event_type1_code' => $unit->event_type1_code,
                'event_type2' => $unit->event_type2,
                'event_type2_code' => $unit->event_type2_code,
                'event_type3' => $unit->event_type3,
                'event_type3_code' => $unit->event_type3_code,
                'unit_name' => $unit->name,
                'unit_name_code' => $unit->name_code,
                'images' => $bindImgs,
            ]);
            if (!StringUtil::isEmpty($params['lat'])) {
                $qrcode->bind_lat = $params['lat'];
            }
            if (!StringUtil::isEmpty($params['lng'])) {
                $qrcode->bind_lng = $params['lng'];
            }
            $qrcode->save();
            $unit->has_bind = 1;
            $unit->qrcode = $qrcode->code;
            $unit->save(true);
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw new $e;
        }

        $this->updateDeploy($unit);
        $this->updateRecord($qrcode->batch_code);

        return [
            'status' => 1,
            'qrcode' => $qrcode,
            'unit' => $unit,
        ];
    }

    private function updateRecord($batchCode)
    {
        $transaction = Yii::$app->test_3->beginTransaction();
        try {
            $record = QrcodeRecord::findOne(['id' => $batchCode]);
            $record->bind_count++;
            $record->save();
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
        }
    }

    private function updateDeploy(Unit $unit)
    {
        $deploy = DeployDetail::findOne(['unit_code' => $unit->unit_code]);
        if (empty($deploy)) {
            return;
        }
        $transaction = Yii::$app->test_3->beginTransaction();
        try {
            $plan = QrcodeDeploy::findOne(['id' => $deploy->deploy_id]);
            $plan->bind_unit_count++;
            $plan->state = ($plan->unit_count == $plan->bind_unit_count) ? 1 : 0;
            $plan->save();
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
        }
    }

    public static function syncHasBind($qrcode) {
        $model = Qrcode::find()->where(['code'=>$qrcode])->one();
        if (empty($model)) {
            throw new InvalidArgumentException('二维码不存在');
        }

        $qrcodeBindCount = QrcodeBind::find()->where(['qrcode'=>$qrcode,'is_delete'=>0])->count();
        if ($qrcodeBindCount <= 1) {
            //只有1个解绑
            $model->has_bind = 0;
        } else {
            $model->has_bind = 1;
        }

//        $qrcodeBind = QrcodeBind::find()->where(['qrcode'=>$qrcode,'is_delete'=>0])->one();
//        if (!empty($qrcodeBind)) {
//            $model->has_bind = 1;
//        } else {
//            $model->has_bind = 0;
//        }

        return $model->save();
    }

    public static function hasQrcodeBind($qrcode) {
        $hasBind = 0;
        $qrcodeBindCount = QrcodeBind::find()->where(['qrcode'=>$qrcode,'is_delete'=>0])->count();
        if ($qrcodeBindCount > 0) {
            $hasBind = 1;
        }
        return $hasBind;
    }

}
